﻿using System;
using System.Diagnostics;
using System.IO;

namespace KnowledgeKiosk
{
    /// <summary>
    /// Provides basic logging functionality through a series of static methods.
    /// </summary>
    /// <remarks>
    /// If FilePath is set the log is written to a file, otherwise the debugger
    /// OutputStream is used. 
    /// </remarks>
    public class Logger
    {
        private static readonly object threadLock = new object();

        /// <summary>
        /// Gets or sets the path of the log file.
        /// </summary>
        public static string FilePath { get; set; }

        public static void WriteLine(Exception e)
        {
            WriteLine("Caught exception: {0} {1}", e.Message, e.StackTrace);
            if (e.InnerException != null) 
                WriteLine(e.InnerException);
        }

        /// <summary>
        /// Writes the text representation of the specified array of objects, followed by the current line terminator, 
        /// to the log using the specified format information.
        /// </summary>
        /// <param name="format">A composite format string.</param>
        /// <param name="args">An array of objects to write using format.</param>
        public static void WriteLine(string format, params object[] args)
        {
            WriteLine(String.Format(format, args));
        }

        /// <summary>
        /// Writes the specified string value, followed by the current line terminator, to the log.
        /// </summary>
        /// <param name="value">The value to write.</param>
        public static void WriteLine(string value)
        {
            value = string.Format("[{0}] {1}", DateTime.Now, value);
            if (!String.IsNullOrEmpty(FilePath))
            {
                lock (threadLock)
                {
                    File.AppendAllText(FilePath, value + "\r\n");
                }
            }
            else
            {
                Debug.WriteLine(value);
            }
        }
    }
}